import { letters } from './data.js';
export const calculateBoxAreaStyle = (xAxisNum, yAxisNum, boxAreaXY) => {
  let { startX, startY, width, height } = boxAreaXY;
  const boxTop = yAxisNum.slice(0, startY).reduce((acc, item) => acc + item.height, 30);
  const boxLeft = xAxisNum.slice(0, startX).reduce((acc, item) => acc + item.width, 50);
  const boxWidth = xAxisNum.slice(startX, startX + width).reduce((acc, item) => acc + item.width, 0);
  const boxHeight = yAxisNum.slice(startY, startY + height).reduce((acc, item) => acc + item.height, 0);
  return { top: boxTop, left: boxLeft, width: boxWidth, height: boxHeight };
};

// 是否点击的是同一个单元格 [x1,y1]和[x2,y2]
export const isClickSameCell = (x1, y1, x2, y2) => x1 != x2 || y1 != y2;

// 比较两个数组是否完全相同
export const compareArray = (arr1, arr2) => JSON.stringify(arr1) === JSON.stringify(arr2);

// 求二维数组每列的最小值
export const getColumnMinimums = (matrix) => matrix[0].map((_, col) => Math.min(...matrix.map((row) => row[col])));

// 获取框选区域所有数据值
export const getBoxAreaData = (data, { height, width, startX, startY }) => {
  return data.slice(startY, startY + height).flatMap((row) => row.cells.slice(startX, startX + width));
};

export const findParentWithClass = (element, className) => {
  // 检查元素是否具有指定的类名
  if (element && element.classList && element.classList.contains(className)) {
    // 如果具有，则返回该元素
    return element;
  } else if (element.parentNode) {
    // 如果不具有，并且有父节点，则递归向上查找
    return findParentWithClass(element.parentNode, className);
  }
  // 如果没有父节点，则返回null
  return null;
};

// 通过坐标查询对应索引
export const getCellIndexByCoord = (coord) => {
  const letter = coord.replace(/\d/g, '');
  const x = letters.findIndex((item) => item === letter);
  const y = parseInt(coord.match(/\d+/)[0], 10) - 1;
  return { x, y };
};

// 生成类似Excel的X轴坐标（即列标)
// ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX']
export const generateXAxisLabels = (startCol, endCol) => {
  const labels = [];
  for (let col = startCol; col <= endCol; col++) {
    let label = '';
    for (let temp = col; temp > 0; temp = Math.floor((temp - 1) / 26)) {
      label = String.fromCharCode(((temp - 1) % 26) + 65) + label;
    }
    labels.push(label);
  }
  return labels;
};

export const canMergeCells = (state) => {
  for (let i = state.boxAreaXY.startY; i <= state.boxAreaXY.startY + state.boxAreaXY.height - 1; i++) {
    for (let j = state.boxAreaXY.startX; j <= state.boxAreaXY.startX + state.boxAreaXY.width - 1; j++) {
      const cell = state.dataJson.rows[i].cells[j];
      if (cell.hide || cell.merge[0] > 1 || cell.merge[1] > 1) {
        return false;
      }
    }
  }
  return true;
};

export const calculateSpan = (state) => {
  const colspan = state.dataJson.rows[state.boxAreaXY.startY].cells.slice(state.boxAreaXY.startX, state.boxAreaXY.endX + 1).reduce((acc, cell) => acc + cell.merge[1], 0);
  const rowspan = state.dataJson.rows.slice(state.boxAreaXY.startY, state.boxAreaXY.endY + 1).reduce((acc, row) => acc + row.cells[state.boxAreaXY.startX].merge[0], 0);
  return { colspan, rowspan };
};

export const hideOtherCells = (state) => {
  for (let i = state.boxAreaXY.startY; i <= state.boxAreaXY.endY; i++) {
    const cells = state.dataJson.rows[i].cells;
    for (let j = state.boxAreaXY.startX; j <= state.boxAreaXY.endX; j++) {
      if (i !== state.boxAreaXY.startY || j !== state.boxAreaXY.startX) {
        Object.assign(cells[j], {
          hide: true,
          type: 'text',
          code: '',
          value: '',
          dicCode: '',
          dicData: [],
          mergeCell: `${state.boxAreaXY.startX}-${state.boxAreaXY.startY}`
        });
        for (const key in cells[j].style) {
          if (key !== 'width' && key !== 'height') {
            delete cells[j].style[key];
          }
        }
      }
    }
  }
};

export const pageSizeInPixels = (pageSize) => {
  var dpi = getDPI();
  var width_mm, height_mm;

  switch (pageSize.toUpperCase()) {
    case 'A0':
      width_mm = 841;
      height_mm = 1189;
      break;
    case 'A1':
      width_mm = 594;
      height_mm = 841;
      break;
    case 'A2':
      width_mm = 420;
      height_mm = 594;
      break;
    case 'A3':
      width_mm = 297;
      height_mm = 420;
      break;
    case 'A4':
      width_mm = 210;
      height_mm = 297;
      break;
    case 'A5':
      width_mm = 148;
      height_mm = 210;
      break;
    case 'B0':
      width_mm = 1000;
      height_mm = 1414;
      break;
    case 'B1':
      width_mm = 707;
      height_mm = 1000;
      break;
    case 'B2':
      width_mm = 500;
      height_mm = 707;
      break;
    case 'B3':
      width_mm = 353;
      height_mm = 500;
      break;
    case 'B4':
      width_mm = 250;
      height_mm = 353;
      break;
    case 'B5':
      width_mm = 176;
      height_mm = 250;
      break;
    default:
      return null;
  }

  var width_px = mmToPixel(width_mm, dpi);
  var height_px = mmToPixel(height_mm, dpi);
  return { width: width_px, height: height_px };
};
export const mmToPixel = (mm, dpi) => {
  // 1 inch = 25.4 mm
  var inches = mm / 25.4;
  var pixels = inches * dpi;
  return Math.round(pixels);
};
export const getDPI = () => {
  var tempDiv = document.createElement('div');
  tempDiv.style.width = '1in';
  tempDiv.style.visibility = 'hidden';
  document.body.appendChild(tempDiv);
  var dpi = tempDiv.offsetWidth;
  document.body.removeChild(tempDiv);
  return dpi;
};
